﻿using Common.Architecture.Common;
using Infrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Reflection;
using System.Text;

namespace Api.Extensions
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 注册链接字符串
        /// </summary>
        /// <typeparam name="TDbContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="connectionString"></param>
        /// <param name="enablesqlLog">是否打印执行My的转义Sql</param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextServie<TDbContext>(this IServiceCollection services, string? connectionString, bool enablesqlLog)where TDbContext : DbContext
        {
            return services.AddDbContext<TDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount:10,
                        maxRetryDelay:TimeSpan.FromSeconds(60),
                        errorNumbersToAdd:null);
                }).EnableSensitiveDataLogging();
                if (enablesqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure => {
                        configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                    }));
                }
            });
        }
        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>
       public static void AddJWT(this IServiceCollection collection,WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options=>
            {
                //取出私钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    ValidateAudience= true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    ValidateLifetime=true,
                    IssuerSigningKey=new SymmetricSecurityKey(secretByte)
                };
            });
        }




        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped(typeof(IBase<>), typeof(Base<>));
            services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            services.AddAutoMapper(typeof(Mappers));
            services.AddScoped<JwtTools>();
            return services;
        }
    }
}
